package com.rongzhong.routing.check;

import java.io.File;
import java.util.Date;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rongzhong.routing.checkNode.TaskNode;
import com.rongzhong.routing.util.Configuration;
import com.rongzhong.routing.util.PerformanceUtil;

/**
 * 
 * @author longxuegang@gmail.com
 * @version 1.0 2011-9-22
 * @since 1.0
 * @see
 */

public class TaskCheck {
	private Configuration configure = Configuration.getInstance();
	private PerformanceUtil perfUtil = PerformanceUtil.getInstance();
	private final String sourcefile = configure.getExcel();
	private final int dbCheckNumber = perfUtil.getDbCheckNumber(); //3
	private static final Logger log = LoggerFactory.getLogger(TaskCheck.class);

	public void checkOutTasks(){
		for (int dbIndex = 0; dbIndex < dbCheckNumber; dbIndex++) {
			TaskNode bean = initTaskNode(dbIndex); 
			try {
				operateExcel(bean);
			} catch (Exception e) {
				log.error("checkOutTasks run into error.",e);
			}finally{
			}
		}
	}
	
	private TaskNode initTaskNode(int dbIndex) {
		TaskNode bean = new TaskNode();
		bean.setDate(new Date(System.currentTimeMillis()));
		bean.setHost(perfUtil.getDBHostPort(dbIndex));
		bean.setCheckDate(perfUtil.getToday());
		return bean;
	}
	
	private void operateExcel(TaskNode bean) throws Exception{
		Workbook workBook = null;
		WritableWorkbook writeWorkBook = null;
		try {
			workBook = Workbook.getWorkbook(new File(sourcefile));
			writeWorkBook = Workbook.createWorkbook(new File(sourcefile), workBook);
			WritableSheet wsheet = writeWorkBook.getSheet(bean.getHost());
			int startColumnId = perfUtil.getStartPositionColumnId(wsheet,perfUtil.getLastReviewDate());
			int startRowId = perfUtil.getStartPositionRowId(wsheet,bean.getTaskNumber());
			Label label_0 = new Label(startColumnId, startRowId, "检查日期 :"+ bean.getCheckDate());
			Label label_1 = new Label(startColumnId, startRowId + 1,"结果");
			wsheet.addCell(label_0);wsheet.addCell(label_1);
			writeWorkBook.write();
		} catch (Exception e) {
			log.error("operate excel run into error", e);
			throw new Exception(e);
		}finally{
			try {
				writeWorkBook.close();workBook.close();
			} catch (Exception e) {
				log.error("close WorkBook run into error",e);
				throw new Exception(e);
			}
		}
	}
}
